<script setup lang="ts">
import { isMobileTerminal } from '@/utils';
import type { ChangeAvatarEmits, ChangeAvatarProps } from './types';
// import { useTemplateRef } from 'vue';
import { useCropper, useOSS } from './composables';
import { ref } from 'vue';
import type OSS from 'ali-oss';
import { useUserStore } from '@/store';
import { MMessage } from '@/libs';

const userStore = useUserStore();

const props = defineProps<ChangeAvatarProps>();
const emits = defineEmits<ChangeAvatarEmits>();

// const imgRef = useTemplateRef<HTMLImageElement>('imgRef');

const close = () => {
  emits('close');
};

const onConfirmClick = async () => {
  loading.value = true;
  const canvas = await cropper.value?.getCropperCanvas()?.$toCanvas();
  canvas?.toBlob(async blob => {
    // console.log(URL.createObjectURL(blob!));
    await putObjectToOSS(blob!);
    loading.value = false;
    close();
    MMessage({
      content: '更新成功',
      type: 'success'
    });
  });
};

const loading = ref<boolean>(false);

const { cropper } = useCropper(props.blob);

let ossClient: OSS;
useOSS().then(res => {
  if (ossClient == null) {
    ossClient = res.ossClient;
  }
});
async function putObjectToOSS(file: Blob) {
  try {
    const extArr = file.type.split('/');
    const ext = extArr[extArr.length - 1];
    const fileName =
      userStore.userInfoGetter?.nickname + '/' + Date.now() + '.' + ext;

    const res = await ossClient.put(`images/${fileName}`, file);
    userStore.updateUserInfo({
      ...userStore.userInfoGetter,
      avatar: res.url
    });
  } catch (err) {
    MMessage({
      content: '上传失败',
      type: 'error'
    });
  }
}

defineOptions({ name: 'ChangeAvatar' });
</script>

<template>
  <div class="flex flex-col items-center overflow-auto">
    <MSvgIcon
      v-if="isMobileTerminal"
      class="m-1 ml-auto h-3 w-3 p-0.5"
      name="close"
      fillClass="fill-zinc-900 dark:bg-zinc-200"
      @click="close"
    />

    <div class="cropper-container w-full xl:h-[400px]"></div>
    <MButton
      class="mt-4 w-[80%] xl:w-1/2"
      @click="onConfirmClick"
      :loading="loading"
    >
      确定
    </MButton>
  </div>
</template>

<style lang="css" scoped>
:deep(cropper-canvas) {
  height: 100%;
}
</style>
